package com.ruyuan.seckilling.render.async.listener;

import com.alibaba.fastjson.JSON;
import com.ruyuan.seckilling.common.FilePathUtils;
import com.ruyuan.seckilling.render.async.BaseRenderPageListener;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.PageRenderEventHolder;
import com.ruyuan.seckilling.render.async.event.Event06SavePageLog;
import com.ruyuan.seckilling.render.entity.PageLog;
import com.ruyuan.seckilling.render.service.PageLogService;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.ruyuan.seckilling.common.ChannelKey.*;
import static com.ruyuan.seckilling.render.async.PageRenderEventHolder.EVENT_07;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(CHANNEL_06_SAVE_PAGE_LOG_MESSAGE)
public class Event06Listener extends BaseRenderPageListener<Event06SavePageLog> {

    @Autowired
    private PageLogService pageLogService;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Event06SavePageLog;
    }

    /**
     * 7、保存流水
     */
    @Override
    protected void doThisStep(Event06SavePageLog event, PageRenderContext context) {
        Runnable task = () -> {
            String staticPagePath = FilePathUtils.generateFilePath(context.getFileName());
            context.setStaticPagePath(staticPagePath);

            PageLog pageLog = context.getPageLog();
            pageLog.setStaticPageUrl(staticPagePath);
            pageLog.setCreateTime(new Date());
            pageLog.setUpdateTime(pageLog.getCreateTime());
            pageLog.setSuccess(true);
            pageLogService.save(pageLog);
            log.info("第6步，保存流水，pageLog={}", JSON.toJSONString(pageLog, true));
            bossEventBus.publish(CHANNEL_07_SEND_PUBLISH_MESSAGE, EVENT_07, context);
        };
        executorService.execute(CHANNEL_06_SAVE_PAGE_LOG_MESSAGE, task);
    }
}
